package org.zhangsh.netty.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import org.zhangsh.socket.HostInfo;
import sun.plugin2.message.EventMessage;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-27
 */
public class EchoClient {

    public static void main(String[] args) throws InterruptedException {

        //
        EventLoopGroup group = new NioEventLoopGroup(1);

        try{
            Bootstrap client = new Bootstrap();
            client.group(group)
                    .remoteAddress(HostInfo.HOST_NAME, HostInfo.HOST_PORT)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, DecoderUtil.DELIMITER_BUF));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new EchoClientHandler());

                        }
                    });

            ChannelFuture sync = client.connect().sync();
            System.out.println(HostInfo.THREAD_NAME + "client start...");

            sync.channel().closeFuture().sync();
            System.out.println(HostInfo.THREAD_NAME + "client stop...");
        } finally {
            group.shutdownGracefully();
        }

    }
}
